package com.wedo.mall.activity.login;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.e.library.entity.User;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EGsonUtils;
import com.wedo.mall.R;
import com.wedo.mall.WApp;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;

/**
 * 绑定第三方账号
 * @author lxy
 * @time 2018/2/6  16:41
 */
public class Binding {

    public static final String TAG = "Binding";
    public User user;
    public Binding(User user){
        this.user = user;
    }

    public void wechat(Context context){
        auth(context, ShareSDK.getPlatform(Wechat.NAME));
    }

    public void facebook(Context context){
        auth(context,ShareSDK.getPlatform(Facebook.NAME));
    }

    private void auth(final Context context, final Platform plat) {
        if (plat.isAuthValid()){
            plat.removeAccount(true);
        }
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
                if (action == Platform.ACTION_USER_INFOR) {

                    Map<String,String> params = new HashMap<>(5);

                    String token = platform.getDb().getToken();
                    String userid = platform.getDb().getUserId();//openid
                    String avatar = platform.getDb().getUserIcon();

                    params.put("user_id",user.id);//绑定账号
                    params.put("openid",userid);
                    params.put("headimgurl",avatar);

                    String name = platform.getName();
                    if (TextUtils.equals(Wechat.NAME, name)) {

                        params.put("unionid",hashMap.get("unionid").toString());
                        params.put("nickname",hashMap.get("nickname").toString());
                        params.put("sign","wechat");

                    } else if (TextUtils.equals(Facebook.NAME,name)){
                        params.put("nickname",hashMap.get("name").toString());
                        params.put("sign","facebook");
                        String json = EGsonUtils.toJson(hashMap);
                        Log.i(TAG,json);
                    }

                    String result = hashMap.toString();
                    Log.i(TAG,result);
                    Log.i(TAG,params.toString());
                    binding(context,name,params);
                }
            }

            @Override
            public void onError(Platform platform, int action, Throwable t) {
                t.printStackTrace();
                if (action == Platform.ACTION_USER_INFOR) {
                    String failure = context.getResources().getString(R.string.auth_failure);
                    sendMessage(MSG_FAILURE,failure);
                }
            }

            @Override
            public void onCancel(Platform platform, int action) {
                if (action == Platform.ACTION_USER_INFOR) {
                }
            }
        });
        //关闭SSO授权
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    /**------第三方登录-----**/
    private void binding(final Context context, final String platform, final Map<String,String> params){
        handler.sendEmptyMessage(MSG_LOADING);
        Observable<EResponse> observable = EClient.with().api().auth(params);
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                if (TextUtils.equals(Wechat.NAME, platform)) {
                    user.wechat = 1;
                } else if (TextUtils.equals(Facebook.NAME,platform)){
                    user.facebook = 1;
                }
                WLogin.saveUser(context,user);
                sendMessage(MSG_SUCCESS,platform);
            }

            @Override
            public void failure(String msg) {
                sendMessage(MSG_FAILURE,msg);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private static final int MSG_LOADING = 0;
    private static final int MSG_SUCCESS = 1;
    private static final int MSG_FAILURE = 2;
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(listener == null) {
                return;
            }
            if(msg.what == MSG_LOADING) {
                listener.loading();
            } else if(msg.what == MSG_SUCCESS) {
                String platform = msg.obj.toString();
                listener.successful(platform);
            } else if(msg.what == MSG_FAILURE) {
                if(msg.obj == null) {
                    String failure = WApp.app().getResources().getString(R.string.auth_failure);
                    listener.failure(failure);
                    return;
                }
                listener.failure(msg.obj.toString());
            }
        }
    };

    private void sendMessage(int what,Object data){
        Message message = handler.obtainMessage(what);
        message.what = what;
        message.obj = data;
        handler.sendMessage(message);
    }

    private BindingListener listener;
    public Binding listener(BindingListener listener){
        this.listener = listener;
        return this;
    }

    public interface BindingListener{
        void loading();
        void successful(String platform);
        void failure(String msg);
    }
}
